import { UPLOAD_FILE_URL } from "@/constants/api";
import Taro from "@tarojs/taro";

export const promisify = (func, ctx) => {
  // 返回一个新的function
  return function () {
    // 初始化this作用域
    var ctx = ctx || this;
    // 新方法返回的promise
    return new Promise((resolve, reject) => {
      // 调用原来的非promise方法func，绑定作用域，传参，以及callback（callback为func的最后一个参数）
      func.call(ctx, ...arguments, function () {
        // 将回调函数中的的第一个参数error单独取出
        var args = Array.prototype.map.call(arguments, item => item);
        var err = args.shift();
        // 判断是否有error
        if (err) {
          reject(err)
        } else {
          // 没有error则将后续参数resolve出来
          args = args.length > 1 ? args : args[0];
          resolve(args);
        }
      });
    })
  };
};

// 下载图片
// export const downLoadImg = (imgurl, msg) => {
//   return new Promise((resolve, reject) => {
//     let that = this
//     wx.downloadFile({
//       url: imgurl,
//       complete: function (res) {
//         console.log(res)
//         if (res.statusCode === 200) {
//           resolve(res.tempFilePath)
//         } else {
//           console.log('downloadstatusCode', res)
//           reject(new Error(res))
//         }
//       },
//       fail: function (res) {
//         console.log('downloadFilefail', res)
//       }
//     })
//   })
// }

export const promiseImage = (url) => {
  return new Promise(function (resolve, reject) {
    resolve(url)
  })
}

export const isChinese = (str) => {
  if (escape(str).indexOf("%u") < 0) return false
  return true
}

export const handleName = (str) => {
  let res = emoj2str(str)
  if (isChinese(res)) {
    res = res.length > 4 ? res.slice(0, 4) + '...' : res
  } else {
    res = res.length > 7 ? res.slice(0, 7) + '...' : res
  }
  return res
}

export const emoj2str = (str) => {
  return unescape(escape(str).replace(/\%uD.{3}/g, ''))
}
/*获取当前页url*/
// export const getCurrentPageUrl = () => {
//   let pages = getCurrentPages()
//   let currentPage = pages[pages.length - 1]
//   let url = currentPage.route
//   return url
// }

export const getSysteminfo = () => {
  let device;
  try {
    let deviceInfo = Taro.getSystemInfoSync()
    device = JSON.stringify(deviceInfo)
  } catch (err) {
    console.error('not support getSystemInfoSync api', err.message)
  }
  return device
}

export const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

export const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export const parseUrlObjToStr = (params) => {
  if (typeof params !== "string") {
    return
  }
  let paramsInfo = JSON.parse(params);
  let paramsUrl = "?";
  Object.keys(paramsInfo).length > 0 ? Object.keys(paramsInfo).forEach(key => {
    paramsUrl += `${key}=${paramsInfo[key]}&`;
  }) : paramsUrl = "";
  return paramsUrl
}

/**
 * 上传图片
 * @param filePath 上传图片的路径
 * @returns 
 */
export const requestUploadFile = (filePath: string, name: string = "pet_upload_file", formData = {}, url = "", isShowLoading=true) => {
  console.log(name, formData, url, filePath);
  
  // 上传图片逻辑
  return new Promise((resolve, reject) => {
    let uploadTask = Taro.uploadFile({
      url: url || `${UPLOAD_FILE_URL}/api/upload_files`,
      filePath,
      name,
      header: {
        "Content-Type": "multipart/form-data",
        "authorization": Taro.getStorageSync('User-Token'),
      },
      ...formData,
      success: (res) => {
        if (res.data) {
          let result: any = JSON.parse(res.data);
          if (!result.result) {
            Taro.showModal({
              title: "上传失败",
              content: result.msg,
              showCancel: false,
            })
            reject(result.msg);
            return;
          }
          resolve(result);
        }
      },
      fail: (err: any) => {
        console.log(err);
        if (err.statusCode !== 200) {
          let data = err.data ? JSON.parse(err.data) : {description: "服务端出错"};
          Taro.showModal({
            title: "上传失败",
            content: data.description,
            showCancel: false,
          })
        }
        reject(err);
      },
      complete: () => {
        Taro.hideLoading();
        uploadTask && uploadTask.abort() // 取消上传任务
      }
    })

    uploadTask.onProgressUpdate((res) => {
      isShowLoading && Taro.showLoading({
        title: `上传进度${res.progress}%`,
        mask: true,
      })
    })
  })
};

export const debounce = (fn, wait) => {
  let timer;
  console.log("防抖函数");
  
  const debounced = function (...args) {
    const context = this;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
      timer = null;
    }, wait);
  };

  // 添加取消方法
  debounced.cancel = function() {
    clearTimeout(timer);
    timer = null;
  };
  
  return debounced;
};